package com.nasarius.bank.scorecard.web.controller.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.nasarius.bank.scorecard.dao.BankDetailsDAO;
import com.nasarius.bank.scorecard.dao.BankFactorsDAO;
import com.nasarius.bank.scorecard.dao.FactorsDAO;
import com.nasarius.bank.scorecard.domain.BankDetails;
import com.nasarius.bank.scorecard.domain.BankFactors;
import com.nasarius.bank.scorecard.domain.Factors;
import com.nasarius.bank.vo.BankManagementVO;

@Controller
public class BankDetailsController {
	 /** Logger that is available to subclasses */
	 protected final Log LOG = LogFactory.getLog(getClass());
	
	@Autowired
	private BankDetailsDAO bankDetailsDAO;
	@Autowired
	private FactorsDAO factorsDAO;
	@Autowired
	private BankFactorsDAO bankFactorsDAO;
	
	@InitBinder
	protected void initBinder(ServletRequestDataBinder binder) {
			binder.registerCustomEditor(List.class,new CustomCollectionEditor(List.class));
			binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
	}
	
	/**
	 * For every request for this controller, this will create a BankDetails
	 * instance for the form .
	 */
	@ModelAttribute
	public BankManagementVO newRequest(@RequestParam(required = false) String bankCode,Model model) {
		List<BankDetails> allBankDetails =null;
		if(bankCode==null){
			allBankDetails =bankDetailsDAO.selectAllBankDetails(); 
		}
		List<Factors> allQuantitativeFactors =factorsDAO.selectAllFactors();
		List<Factors> allFactors = new ArrayList<Factors>();		
		List<BankFactors> bankfactors=null;
		List<BankFactors> allBankfactors=new ArrayList<BankFactors>();
		if(bankCode!=null){
			model.addAttribute("update","Y");
			bankfactors=bankFactorsDAO.selectBankFactorsByBankCode(bankCode);
		}
		for(Factors factor: allQuantitativeFactors){
			if (factor != null && factor.getFactortype() != null && factor.getFactortype().equalsIgnoreCase("Quantitative")){
				allFactors.add(factor);
			}
		}
		for(Factors factor:allFactors){
			BankFactors bFactors= new BankFactors();
			bFactors.setFactorid(factor.getFactorid());
			bFactors.setFactorName(factor.getFactorname());
			bFactors.setUnits(factor.getUnits());
			if(bankCode!=null){
				bFactors.setBankcode(bankCode);
				for(BankFactors bankFactor:bankfactors){
					if(bankFactor.getFactorid().equals(factor.getFactorid())){
						bFactors=bankFactor;
						break;
					}
				}
			}
			allBankfactors.add(bFactors);
		}
		model.addAttribute("allBankDetails", allBankDetails);
		BankManagementVO b=new  BankManagementVO();
		b.setSelectedBankCode(bankCode);
		b.setBankfactors(allBankfactors);
		b.setBankDetails(bankCode!=null? bankDetailsDAO.selectBankDetailsByPrimaryKey(bankCode):new BankDetails());
		return b;
	}
	
	   /**
     * <p>Person form request.</p>
     * 
     * <p>Expected HTTP GET and request '/bankdetails/view'.</p>
     */
    @RequestMapping(value="/bankdetails/view", method=RequestMethod.GET)
    public void form() {}
    
    /**
     * <p>Person form request.</p>
     * 
     * <p>Expected HTTP GET and request '/bankdetails/view'.</p>
     */
    @RequestMapping(value="/bankdetails/edit", method=RequestMethod.GET)
    public void edit() {}
    
    /**
     * <p>Saves a person.</p>
     * 
     * <p>Expected HTTP POST and request '/bankdetails/add'.</p>
     */
    @RequestMapping(value="/bankdetails/add", method=RequestMethod.POST)
    public void add(BankManagementVO bankManagementVO, Model model) {
    	LOG.info("factor"+bankManagementVO.getBankfactors());
    	
    	for(BankFactors f:bankManagementVO.getBankfactors()){
    		LOG.info("factor"+f.getFactorid());
    		LOG.info("bank"+f.getBankcode());
    		
    	}
    	if(bankDetailsDAO.selectBankDetailsByPrimaryKey(bankManagementVO.getBankDetails().getBankcode()) == null){
    	bankDetailsDAO.insertBankDetails(bankManagementVO.getBankDetails());
    	int i=0;
    	Date fromDate = null;
    	Date toDate=null;
    	for(BankFactors bankFactors:bankManagementVO.getBankfactors()){
    		if(i==0){
    			fromDate=bankFactors.getFromdt();
    			toDate=bankFactors.getTodt();
    			i++;
    		}
    		bankFactors.setBankcode(bankManagementVO.getBankDetails().getBankcode());
    		if(bankFactors.getBankcode()!=null && !bankFactors.getBankcode().equals("") && bankFactors.getExpectedvalue() != null){
    			bankFactors.setFromdt(fromDate);
    			bankFactors.setTodt(toDate);
    			if(bankFactorsDAO.selectBankFactorsByPrimaryKey(bankFactors.getBankcode(), bankFactors.getFactorid())==null){
    				bankFactorsDAO.insertBankFactors(bankFactors);
    			}
    			else{
    				bankFactorsDAO.updateBankFactorsByPrimaryKeySelective(bankFactors);
    			}
    		}
    	}
		model.addAttribute("updated","Y");
    	}else{
    		model.addAttribute("bankExist", "Y");
    	}
        /*if (person.getCreated() == null) {
            person.setCreated(new Date());
        }*/

        //Person result = personDao.save(person);
        
        // set id from create
        /*if (person.getId() == null) {
            person.setId(result.getId());
        }*/
    	
    }
    
    @RequestMapping(value="/bankdetails/update", method=RequestMethod.POST)
    public void update(BankManagementVO bankManagementVO, Model model) {
    	LOG.info("factor"+bankManagementVO.getBankfactors());
    	
    	for(BankFactors f:bankManagementVO.getBankfactors()){
    		LOG.info("factor"+f.getFactorid());
    		LOG.info("bank"+f.getBankcode());
    		
    	}
    	bankDetailsDAO.updateBankDetailsByPrimaryKey(bankManagementVO.getBankDetails());
    	int i=0;
    	Date fromDate = null;
    	Date toDate=null;
    	for(BankFactors bankFactors:bankManagementVO.getBankfactors()){
    		if(i==0){
    			fromDate=bankFactors.getFromdt();
    			toDate=bankFactors.getTodt();
    			i++;
    		}
    		if(bankFactors.getBankcode()!=null && !bankFactors.getBankcode().equals("") && bankFactors.getExpectedvalue() != null){
    			bankFactors.setFromdt(fromDate);
    			bankFactors.setTodt(toDate);
    			if(bankFactorsDAO.selectBankFactorsByPrimaryKey(bankFactors.getBankcode(), bankFactors.getFactorid())==null)
    				bankFactorsDAO.insertBankFactors(bankFactors);
    			else
    				bankFactorsDAO.updateBankFactorsByPrimaryKeySelective(bankFactors);
    		}
    		
    	}
        /*if (person.getCreated() == null) {
            person.setCreated(new Date());
        }*/

        //Person result = personDao.save(person);
        
        // set id from create
        /*if (person.getId() == null) {
            person.setId(result.getId());
        }*/
    	
        //model.addAttribute("statusMessageKey", "person.form.msg.success");
		model.addAttribute("updated","Y");
    }
    
    
    public void setBankDetailsDAO(BankDetailsDAO bankDetailsDAO) {
		this.bankDetailsDAO = bankDetailsDAO;
	}
    public void setFactorsDAO(FactorsDAO factorsDAO) {
		this.factorsDAO = factorsDAO;
	}
    public void setBankFactorsDAO(BankFactorsDAO bankFactorsDAO) {
		this.bankFactorsDAO = bankFactorsDAO;
	}
}
